import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { User } from './entities/user.entity';
import { Role } from './entities/role.entity';
import { Permission } from './entities/permission.entity';
import { InjectEntityManager } from '@nestjs/typeorm';
import { EntityManager, In } from 'typeorm';
import { UserLoginDto } from './dto/user-login.dto';


@Injectable()
export class UserService {

  @InjectEntityManager()
  entityManager: EntityManager


  async findRolesByIds(roleIds: number[]) {
    return this.entityManager.find(Role, {
      where: {
        id: In(roleIds)
      },
      relations: {
        permissions: true
      }
    });
}
  async login(userlogin: UserLoginDto) {

    const user = await this.entityManager.findOne(User, {
      where: { username: userlogin.username },
      relations: { roles: true }
    });


    if(!user) {
      throw new HttpException('用户不存在', HttpStatus.ACCEPTED);
    }

    if(user.password !== userlogin.password) {
      throw new HttpException('密码错误', HttpStatus.ACCEPTED);
    }

    return user;

  }

  async initData(){
      const user1 = new User();
      user1.username = '张三';
      user1.password = '111111';

      const user2 = new User();
      user2.username = '李四';
      user2.password = '222222';

      const user3 = new User();
      user3.username = '王五';
      user3.password = '333333';

      const role1 = new Role();
      role1.name = 'admin';

      const role2 = new Role();
      role2.name = 'regular_user';

      const permission1 = new Permission();
      permission1.name = 'create_aaa';

      const permission2 = new Permission();
      permission2.name = 'update_aaa';

      const permission3 = new Permission();
      permission3.name = 'remove_aaa';

      const permission4 = new Permission();
      permission4.name = 'query_aaa';

      const permission5 = new Permission();
      permission5.name = 'create_bbb';

      const permission6 = new Permission();
      permission6.name = 'update_bbb';

      const permission7 = new Permission();
      permission7.name = 'remove_bbb';

      const permission8 = new Permission();
      permission8.name = 'query_bbb';

      role1.permissions = [permission1, permission2, permission3, permission4, permission5, permission6, permission7, permission8];
      role2.permissions = [permission1, permission2, permission3, permission4];

      user1.roles = [role1];
      user2.roles = [role2];

      await this.entityManager.save(Permission, [
        permission1, permission2, permission3, permission4, permission5, permission6, permission7, permission8
      ])

      await this.entityManager.save(Role, [role1, role2]);

      await this.entityManager.save(User, [user1, user2, user3]);

  }

  }
